<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;

class WeChatService
{
    protected $appId;
    protected $appSecret;
    protected $accessToken;

    public function __construct()
    {
        $this->appId = config('wechat.app_id'); // 从配置文件中获取
        $this->appSecret = config('wechat.secret'); // 从配置文件中获取
        $this->accessToken = $this->getAccessToken(); // 获取 access_token
    }

    /**
     * 获取 access_token
     *
     * @return string
     */
    protected function getAccessToken()
    {
        // 假设你有一个缓存 access_token 的逻辑
        // 例如: Cache::get('wechat_access_token');
        $response = Http::get("https://api.weixin.qq.com/cgi-bin/token", [
            'grant_type' => 'client_credential',
            'appid' => $this->appId,
            'secret' => $this->appSecret,
        ]);

        $data = $response->json();
        //var_dump($data);die;
        if (isset($data['access_token'])) {
            // Cache::put('wechat_access_token', $data['access_token'], 7000); // 过期时间设置为7000秒
            return $data['access_token'];
        }

        throw new \Exception('Failed to get access_token.');
    }

    /**
     * 通过 unionID 反查 openID
     *
     * @param string $unionId
     * @return string|null
     * @throws \Exception
     */
    public function getOpenIdByUnionId($unionId)
    {
        // 获取所有公众号中该 unionId 的用户信息
        $response = Http::get("https://api.weixin.qq.com/cgi-bin/user/info", [
            'access_token' => $this->accessToken,
            'unionid' => $unionId,
            'lang' => 'zh_CN'
        ]);
        // var_dump($response);die;
        $data = $response->json();

        if (isset($data['openid'])) {
            return $data['openid'];
        }

        throw new \Exception('No openid found for the given unionid.');
    }
}
